from django.shortcuts import render

# Create your views here.

from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password,check_password
from django.http import JsonResponse
from ..models import *
import time


# 登录页
def login(request):
    return render(request,'login.html')
# 执行登录
def doLogin(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken",None)
    # 先检测学生表
    user_obj = UserMsg.objects.filter(username=data['username']).first()
    if not user_obj:
        return JsonResponse ({'msg': '登录失败！帐号不存在！', 'code': 403})
    else:
        # 检测密码是否正确
        res = check_password (data['password'], user_obj.password)
        if not res:
            return JsonResponse ({'msg': '登录失败！密码错误！', 'code': 403})
        else:
            # 生成session身份认证
            request.session['user'] = data
            return JsonResponse ({'msg': '登录成功！', 'code': 200})

# 注册页
def register(request):
    return render(request,'register.html')
# 执行注册
def doRegister(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken",None)
    # 添加注册时间
    isExist = False
    data['register_time'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    data['is_delete'] = '0'
    # 密码加密
    data['password'] = make_password (data['password'], None, 'pbkdf2_sha256')

    # 查询是否帐号已经被注册
    obj = UserMsg.objects.filter(username=data['username']).first()
    if not obj:
        UserMsg(**data).save()
        return JsonResponse ({'msg': '注册成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '当前用户昵称已经被注册，请重新输入！', 'code': 403})


## 执行退出登录
def doLogout(request):
    request.session.flush()
    print("退出登录成功")
    return redirect("myhome_login")

# 后台主页
def index(request):
    return render(request,'index.html')


# 管理平台主页
def welcome(request):
    data_list1 = UserMsg.objects.filter ().order_by ('register_time')[:5]
    data_list = data_list1 if  data_list1 else []
    show_data = {
        'show_count1':'42,323',
        'show_add1':'423',
        'show_count2':'32,323',
        'show_add2':'342',
        'show_count3':'234,234',
        'show_add3':'233',
    }

    return render(request,'welcome.html',{'data_list':data_list,'show_data':show_data})

# 404页
def empty(request):
    return render(request,'404error.html')

